"use client"

import { useState, useRef } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Platform, Animated, Dimensions, Image, Alert } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ArrowLeft, Volume2, CheckCircle2, XCircle, HelpCircle, List } from "lucide-react-native"
import { useRouter } from "expo-router"
import { theme } from "../../constants/theme"
import { WordListModal, type WordListItem } from "../../components/practices/WordListModal"
import { ProgressBar } from "../../components/practices/ProgressBar"

// 获取屏幕尺寸
const { width } = Dimensions.get("window")
const isTablet = width > 768

// 模拟的练习数据
const PRACTICE_DATA = [
    {
        id: "1",
        word: "apple",
        phonetic: "/ˈæp.əl/",
        options: [
            { id: "a", text: "苹果", correct: true },
            { id: "b", text: "香蕉", correct: false },
            { id: "c", text: "橙子", correct: false },
            { id: "d", text: "梨子", correct: false },
        ],
    },
    {
        id: "2",
        word: "book",
        phonetic: "/bʊk/",
        options: [
            { id: "a", text: "书本", correct: true },
            { id: "b", text: "笔记本", correct: false },
            { id: "c", text: "铅笔", correct: false },
            { id: "d", text: "橡皮", correct: false },
        ],
    },
    {
        id: "3",
        word: "cat",
        phonetic: "/kæt/",
        options: [
            { id: "a", text: "猫", correct: true },
            { id: "b", text: "狗", correct: false },
            { id: "c", text: "老鼠", correct: false },
            { id: "d", text: "兔子", correct: false },
        ],
    },
    {
        id: "4",
        word: "dog",
        phonetic: "/dɒɡ/",
        options: [
            { id: "a", text: "狗", correct: true },
            { id: "b", text: "猫", correct: false },
            { id: "c", text: "鸟", correct: false },
            { id: "d", text: "鱼", correct: false },
        ],
    },
    {
        id: "5",
        word: "elephant",
        phonetic: "/ˈel.ɪ.fənt/",
        options: [
            { id: "a", text: "大象", correct: true },
            { id: "b", text: "长颈鹿", correct: false },
            { id: "c", text: "狮子", correct: false },
            { id: "d", text: "老虎", correct: false },
        ],
    },
]

export default function EnglishChoiceScreen() {
    const router = useRouter()
    const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
    const [selectedOption, setSelectedOption] = useState<string | null>(null)
    const [isCorrect, setIsCorrect] = useState<boolean | null>(null)
    const [score, setScore] = useState(0)
    const [showFeedback, setShowFeedback] = useState(false)
    const [isPlaying, setIsPlaying] = useState(false)
    const [completed, setCompleted] = useState(false)
    const [listModalVisible, setListModalVisible] = useState(false)

    // 动画值
    const fadeAnim = useRef(new Animated.Value(1)).current
    const scaleAnim = useRef(new Animated.Value(1)).current
    const feedbackAnim = useRef(new Animated.Value(0)).current
    const correctAnim = useRef(new Animated.Value(1)).current
    const pulseAnim = useRef(new Animated.Value(1)).current

    // 当前问题
    const currentQuestion = PRACTICE_DATA[currentQuestionIndex]

    // 处理选项选择
    const handleOptionSelect = (optionId: string) => {
        if (selectedOption !== null) return // 已经选择了选项，不允许再次选择

        const option = currentQuestion.options.find((opt) => opt.id === optionId)
        if (!option) return

        setSelectedOption(optionId)
        setIsCorrect(option.correct)
        setShowFeedback(true)

        if (option.correct) {
            setScore(score + 1)
            // 播放正确音效
            playCorrectSound()
            // 播放正确动画
            Animated.sequence([
                Animated.timing(correctAnim, {
                    toValue: 1.2,
                    duration: 200,
                    useNativeDriver: true,
                }),
                Animated.timing(correctAnim, {
                    toValue: 1,
                    duration: 200,
                    useNativeDriver: true,
                }),
            ]).start()

            // 脉冲动画
            Animated.loop(
                Animated.sequence([
                    Animated.timing(pulseAnim, {
                        toValue: 1.05,
                        duration: 500,
                        useNativeDriver: true,
                    }),
                    Animated.timing(pulseAnim, {
                        toValue: 1,
                        duration: 500,
                        useNativeDriver: true,
                    }),
                ]),
                { iterations: 3 },
            ).start()
        } else {
            // 播放错误音效
            playWrongSound()
            // 显示错误反馈，然后自动消失
            Animated.sequence([
                Animated.timing(feedbackAnim, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.delay(1500),
                Animated.timing(feedbackAnim, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }),
            ]).start(() => {
                setShowFeedback(false)
                setSelectedOption(null)
                setIsCorrect(null)
            })
        }
    }

    // 模拟播放正确音效
    const playCorrectSound = () => {
        console.log("播放正确音效")
    }

    // 模拟播放错误音效
    const playWrongSound = () => {
        console.log("播放错误音效")
    }

    // 模拟播放单词发音
    const playWordSound = () => {
        if (isPlaying) return

        setIsPlaying(true)
        console.log(`播放单词: ${currentQuestion.word}`)

        // 模拟播放完成
        setTimeout(() => {
            setIsPlaying(false)
        }, 1500)
    }

    // 下一题
    const handleNext = () => {
        if (currentQuestionIndex < PRACTICE_DATA.length - 1) {
            // 淡出当前问题
            Animated.parallel([
                Animated.timing(fadeAnim, {
                    toValue: 0,
                    duration: 200,
                    useNativeDriver: true,
                }),
                Animated.timing(scaleAnim, {
                    toValue: 0.8,
                    duration: 200,
                    useNativeDriver: true,
                }),
            ]).start(() => {
                setCurrentQuestionIndex(currentQuestionIndex + 1)
                setSelectedOption(null)
                setIsCorrect(null)
                setShowFeedback(false)

                // 淡入新问题
                Animated.parallel([
                    Animated.timing(fadeAnim, {
                        toValue: 1,
                        duration: 200,
                        useNativeDriver: true,
                    }),
                    Animated.timing(scaleAnim, {
                        toValue: 1,
                        duration: 200,
                        useNativeDriver: true,
                    }),
                ]).start()
            })
        } else {
            // 练习完成
            setCompleted(true)
        }
    }

    // 返回上一页
    const handleBack = () => {
        if (selectedOption !== null) {
            // 如果已经选择了答案但还没进入下一题，弹出确认框
            Alert.alert(
                "确认返回",
                "练习尚未完成，确定要返回吗？",
                [
                    { text: "取消", style: "cancel" },
                    { text: "确定", onPress: () => router.back() },
                ],
                { cancelable: true },
            )
        } else {
            router.back()
        }
    }

    // 完成练习
    const handleComplete = () => {
        router.back()
    }

    // 重新开始
    const handleRestart = () => {
        setCurrentQuestionIndex(0)
        setSelectedOption(null)
        setIsCorrect(null)
        setShowFeedback(false)
        setScore(0)
        setCompleted(false)
    }

    // 获取选项样式
    const getOptionStyle = (optionId: string) => {
        if (selectedOption === optionId) {
            if (isCorrect) {
                return [styles.option, styles.optionCorrect]
            } else {
                return [styles.option, styles.optionWrong]
            }
        }
        return [styles.option]
    }

    // 获取选项文本样式
    const getOptionTextStyle = (optionId: string) => {
        if (selectedOption === optionId) {
            if (isCorrect) {
                return [styles.optionText, styles.optionTextCorrect]
            } else {
                return [styles.optionText, styles.optionTextWrong]
            }
        }
        return [styles.optionText]
    }

    // 跳转到指定题目
    const jumpToQuestion = (index: number) => {
        if (index === currentQuestionIndex) {
            setListModalVisible(false)
            return
        }

        setCurrentQuestionIndex(index)
        setSelectedOption(null)
        setIsCorrect(null)
        setShowFeedback(false)
        setListModalVisible(false)
    }

    // 准备单词列表数据
    const wordListData: WordListItem[] = PRACTICE_DATA.map((item) => ({
        id: item.id,
        word: item.word,
        phonetic: item.phonetic,
    }))

    // 渲染完成页面
    if (completed) {
        return (
            <SafeAreaView style={styles.container} edges={["top"]}>
                <LinearGradient
                    colors={theme.colors.neutral.backgroundGradient}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                    style={styles.gradientBackground}
                >
                    <View style={styles.header}>
                        <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                            <ArrowLeft size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>
                        <Text style={styles.headerTitle}>英文选义</Text>
                        <View style={{ width: 40 }} />
                    </View>

                    <View style={styles.completedContainer}>
                        <Image
                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341047.png" }}
                            style={styles.completedImage}
                        />
                        <Text style={styles.completedTitle}>练习完成！</Text>
                        <Text style={styles.completedScore}>
                            得分: {score}/{PRACTICE_DATA.length}
                        </Text>
                        <Text style={styles.completedMessage}>
                            {score === PRACTICE_DATA.length
                                ? "太棒了！你答对了所有题目！"
                                : score >= PRACTICE_DATA.length / 2
                                    ? "做得不错！再接再厉！"
                                    : "继续努力，你会做得更好！"}
                        </Text>

                        <View style={styles.completedButtons}>
                            <TouchableOpacity style={styles.restartButton} onPress={handleRestart}>
                                <Text style={styles.restartButtonText}>再来一次</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={styles.completeButton} onPress={handleComplete}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.completeButtonGradient}
                                >
                                    <Text style={styles.completeButtonText}>完成练习</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>
                    </View>
                </LinearGradient>
            </SafeAreaView>
        )
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部 */}
                <View style={styles.header}>
                    <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                        <ArrowLeft size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>英文选义</Text>
                    <TouchableOpacity onPress={() => setListModalVisible(true)} style={styles.listButton}>
                        <List size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                </View>

                {/* 进度条 */}
                <ProgressBar
                    current={currentQuestionIndex + 1}
                    total={PRACTICE_DATA.length}
                    showText={true}
                    textPosition="top"
                />

                {/* 问题卡片 */}
                <Animated.View
                    style={[
                        styles.questionCard,
                        {
                            opacity: fadeAnim,
                            transform: [{ scale: scaleAnim }],
                        },
                    ]}
                >
                    <View style={styles.wordContainer}>
                        <Text style={styles.word}>{currentQuestion.word}</Text>
                        <TouchableOpacity
                            style={styles.soundButton}
                            onPress={playWordSound}
                            disabled={isPlaying}
                            activeOpacity={0.7}
                        >
                            <Volume2 size={24} color={theme.colors.primary.default} />
                        </TouchableOpacity>
                    </View>
                    <Text style={styles.phonetic}>{currentQuestion.phonetic}</Text>

                    {/* 选项 */}
                    <View style={styles.optionsContainer}>
                        {currentQuestion.options.map((option) => (
                            <TouchableOpacity
                                key={option.id}
                                style={getOptionStyle(option.id)}
                                onPress={() => handleOptionSelect(option.id)}
                                disabled={selectedOption !== null}
                                activeOpacity={0.8}
                            >
                                <Text style={getOptionTextStyle(option.id)}>{option.text}</Text>
                                {selectedOption === option.id && isCorrect && (
                                    <Animated.View
                                        style={{
                                            transform: [{ scale: correctAnim }],
                                        }}
                                    >
                                        <CheckCircle2 size={20} color={theme.colors.secondary.green.default} />
                                    </Animated.View>
                                )}
                                {selectedOption === option.id && !isCorrect && (
                                    <XCircle size={20} color={theme.colors.secondary.red.default} />
                                )}
                            </TouchableOpacity>
                        ))}
                    </View>

                    {/* 提示和反馈 */}
                    <View style={styles.feedbackArea}>
                        {!showFeedback && (
                            <View style={styles.hintContainer}>
                                <HelpCircle size={16} color={theme.colors.neutral.gray} />
                                <Text style={styles.hintText}>选择与单词对应的中文意思</Text>
                            </View>
                        )}

                        {showFeedback && !isCorrect && (
                            <Animated.View
                                style={[
                                    styles.feedbackContainer,
                                    styles.feedbackWrong,
                                    {
                                        opacity: feedbackAnim,
                                        transform: [
                                            {
                                                translateY: feedbackAnim.interpolate({
                                                    inputRange: [0, 1],
                                                    outputRange: [10, 0],
                                                }),
                                            },
                                        ],
                                    },
                                ]}
                            >
                                <XCircle size={16} color={theme.colors.secondary.red.default} />
                                <Text style={[styles.feedbackText, styles.feedbackTextWrong]}>回答错误！</Text>
                            </Animated.View>
                        )}

                        {showFeedback && isCorrect && (
                            <Animated.View
                                style={[
                                    styles.feedbackContainer,
                                    styles.feedbackCorrect,
                                    {
                                        transform: [{ scale: pulseAnim }],
                                    },
                                ]}
                            >
                                <CheckCircle2 size={16} color={theme.colors.secondary.green.default} />
                                <Text style={[styles.feedbackText, styles.feedbackTextCorrect]}>答对了！</Text>
                            </Animated.View>
                        )}
                    </View>
                </Animated.View>

                {/* 底部按钮 */}
                <View style={styles.bottomContainer}>
                    {showFeedback && isCorrect && (
                        <TouchableOpacity style={styles.nextButton} onPress={handleNext}>
                            <LinearGradient
                                colors={theme.colors.primary.gradient}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                                style={styles.nextButtonGradient}
                            >
                                <Text style={styles.nextButtonText}>
                                    {currentQuestionIndex < PRACTICE_DATA.length - 1 ? "下一题" : "完成"}
                                </Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    )}
                </View>

                {/* 单词列表弹窗 */}
                <WordListModal
                    visible={listModalVisible}
                    data={wordListData}
                    currentIndex={currentQuestionIndex}
                    onClose={() => setListModalVisible(false)}
                    onSelectWord={jumpToQuestion}
                    title="单词列表"
                />
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    listButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    questionCard: {
        flex: 1,
        marginHorizontal: theme.spacing.lg,
        marginBottom: theme.spacing.lg,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    wordContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.sm,
    },
    word: {
        fontSize: isTablet ? 48 : 36,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        textAlign: "center",
    },
    soundButton: {
        marginLeft: theme.spacing.md,
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        textAlign: "center",
        marginBottom: theme.spacing.xl,
    },
    optionsContainer: {
        flex: 1,
        justifyContent: "center",
        gap: theme.spacing.lg,
    },
    option: {
        backgroundColor: "rgba(91, 142, 244, 0.05)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderWidth: 2,
        borderColor: "transparent",
        minHeight: 60, // 固定高度，避免选择后布局变化
    },
    optionCorrect: {
        borderColor: theme.colors.secondary.green.default,
        backgroundColor: "rgba(52, 199, 89, 0.1)",
    },
    optionWrong: {
        borderColor: theme.colors.secondary.red.default,
        backgroundColor: "rgba(255, 59, 48, 0.1)",
    },
    optionText: {
        fontSize: isTablet ? theme.fontSize.lg : theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.medium,
    },
    optionTextCorrect: {
        color: theme.colors.secondary.green.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    optionTextWrong: {
        color: theme.colors.secondary.red.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    feedbackArea: {
        height: 40, // 固定高度，避免反馈显示时布局变化
        justifyContent: "center",
        alignItems: "center",
        marginTop: theme.spacing.lg,
    },
    hintContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        gap: theme.spacing.xs,
    },
    hintText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
    },
    feedbackContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        gap: theme.spacing.xs,
    },
    feedbackCorrect: {
        backgroundColor: "rgba(52, 199, 89, 0.1)",
    },
    feedbackWrong: {
        backgroundColor: "rgba(255, 59, 48, 0.1)",
    },
    feedbackText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
    feedbackTextCorrect: {
        color: theme.colors.secondary.green.default,
    },
    feedbackTextWrong: {
        color: theme.colors.secondary.red.default,
    },
    bottomContainer: {
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
    },
    nextButton: {
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    nextButtonGradient: {
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    nextButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
    // 完成页面样式
    completedContainer: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: theme.spacing.xl,
    },
    completedImage: {
        width: 150,
        height: 150,
        marginBottom: theme.spacing.xl,
    },
    completedTitle: {
        fontSize: isTablet ? 36 : 28,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.lg,
    },
    completedScore: {
        fontSize: isTablet ? theme.fontSize.xl : theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.md,
    },
    completedMessage: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        textAlign: "center",
        marginBottom: theme.spacing.xxxl,
    },
    completedButtons: {
        flexDirection: "row",
        gap: theme.spacing.lg,
        width: "100%",
        maxWidth: 400,
    },
    restartButton: {
        flex: 1,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    restartButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    completeButton: {
        flex: 1,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    completeButtonGradient: {
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    completeButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
})

